package com.cug.smartranch.animal.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cug.smartranch.animal.admin.dao.entity.EnvironmentMonitoring;
import com.cug.smartranch.animal.admin.dao.mapper.EnvironmentMonitoringMapper;
import com.cug.smartranch.animal.admin.dto.req.EnvironmentMonitoringReqDTO;
import com.cug.smartranch.animal.admin.dto.resp.EnvironmentMonitoringRespDTO;
import com.cug.smartranch.animal.admin.service.EnvironmentMonitoringService;
import com.cug.smartranch.framework.exception.ClientException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 环境监测记录业务逻辑实现层
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EnvironmentMonitoringServiceImpl extends ServiceImpl<EnvironmentMonitoringMapper, EnvironmentMonitoring> implements EnvironmentMonitoringService {
    private final EnvironmentMonitoringMapper environmentMonitoringMapper;
    @Override
    public void createEnvironment() {
        // 校验是否超过300条记录，如果超过就不让创建了
        LambdaQueryWrapper<EnvironmentMonitoring> queryWrapper = Wrappers.lambdaQuery(EnvironmentMonitoring.class);
        List<EnvironmentMonitoring> list = environmentMonitoringMapper.selectList(queryWrapper);
        int size = list.size();
        if (size > 300) {
            throw new ClientException("已经超过300条环境记录了，别创建了哥~~");
        }

        // 生成300条日期记录，距当前时间之前300天的每一天
        List<Date> dateList = generate300Days();

        //创建三百条（正常范围内）环境记录
        List<EnvironmentMonitoring> environmentDataList = new ArrayList<>();
        int index=0;
        for (int i = 0; i < 300; i++) {
            EnvironmentMonitoring data = new EnvironmentMonitoring();
            // 生成数据在正常范围内
            data.setTemperature(generateRandomValue(18.00, 35.00));
            data.setHumidity(generateRandomValue(40.00, 70.00));
            data.setPressure(generateRandomValue(1000.00, 1025.00));
            data.setLightIntensity(generateRandomValue(1000.00, 10000.00));
            data.setO2Level(generateRandomValue(190000.00, 210000.00));
            data.setCo2Level(generateRandomValue(350.00, 500.00));
            data.setPm25(generateRandomValue(0.00, 35.00));
            data.setWindSpeed(generateRandomValue(0.00, 5.00));
            data.setSoilMoisture(generateRandomValue(20.00, 50.00));
            // 默认创建时间和更新时间
            Date date = dateList.get(index++);
            data.setCreateTime(date);
            data.setUpdateTime(date);
            environmentDataList.add(data);
        }
        // 使用 MyBatis-Plus 批量插入
        environmentMonitoringMapper.insert(environmentDataList);
    }

    /**
     * 获取监测环境记录
     * @param requestParam
     * @return 监测环境记录
     */
    @Override
    public Map<Date, EnvironmentMonitoringRespDTO> getEnvironment(EnvironmentMonitoringReqDTO requestParam) {
        Date startDate = new Date(requestParam.getStartDate());
        Date endDate = new Date(requestParam.getEndDate());
        // 创建一个列表来存放日期对象
        List<Date> dateList = new ArrayList<>();
        // 使用一个循环来添加从开始时间到结束时间的每个日期
        Date currentDate = startDate;
        while (currentDate.compareTo(endDate) <= 0) {
            dateList.add(currentDate); // 将当前日期添加到列表中
            currentDate = DateUtil.offsetDay(currentDate, 1); // 增加一天
        }
        if(dateList.size()>10){
            throw new ClientException("开始时间和结束时间不能超过10天");
        }
        // 查詢
        LambdaQueryWrapper<EnvironmentMonitoring> queryWrapper = Wrappers.lambdaQuery(EnvironmentMonitoring.class);
        queryWrapper.in(EnvironmentMonitoring::getCreateTime, dateList);
        List<EnvironmentMonitoring> list = environmentMonitoringMapper.selectList(queryWrapper);
        // 转换为respDTO
        List<EnvironmentMonitoringRespDTO> tempResult = new ArrayList<>();
        for (EnvironmentMonitoring e : list) {
            EnvironmentMonitoringRespDTO respDTO = BeanUtil.toBean(e, EnvironmentMonitoringRespDTO.class);
            respDTO.setDate(e.getCreateTime());
            tempResult.add(respDTO);
        }
        // 相同date，保留一个
        Map<Date, EnvironmentMonitoringRespDTO> result = tempResult.stream()
                .collect(Collectors.toMap(EnvironmentMonitoringRespDTO::getDate, dto -> dto, (x1, x2) -> x1));
        return result;
    }

    /**
     * 生成300条日期记录，距当前时间之前300天的每一天
     * @return 300条日期记录
     */
    private List<Date> generate300Days() {
        // 当前日期
        LocalDate currentDate = LocalDate.now();
        // 用于存储生成的日期记录
        List<Date> dateRecords = new ArrayList<>();
        // 向前推 300 天，每天都生成一条记录
        int daysBack = 300;
        for (int i = 0; i < daysBack; i++) {
            // 当前日期减去 i 天
            LocalDate recordDate = currentDate.minusDays(i);
            Date dateData = Date.from(recordDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            dateRecords.add(dateData);
        }
        return dateRecords;
    }

    // 生成指定范围内的随机数
    private BigDecimal generateRandomValue(Double min, Double max) {
        double tempResult = min + (max - min) * Math.random();
        BigDecimal result = BigDecimal.valueOf(tempResult);
        return result;
    }


}
